﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FairyWorld.Models;
using System.Data.Entity;
using System.IO;
using System.Net.Mail;

namespace FairyWorld.Controllers
{
    public class GroupController : Controller
    {
        //
        // GET: /Group/
        const int space = 1024 * 1024 * 200;
        SrcManager srcDB = new SrcManager();        

        /// <summary>
        /// 首页跳转到所有文件栏
        /// </summary>
        /// <param name="id">组ID</param>
        /// <returns>所有文件视图</returns>
        public ActionResult Index(int id)
        {
            this.HttpContext.Session["group"] = id;
            return RedirectToAction("Files");
        }

        /// <summary>
        /// 联系人与信息传递视图
        /// </summary>
        /// <returns>联系视图</returns>
        public ActionResult Contact()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Group group = GetGroup("roles.user");
            User user = GetUser("roles");
            ViewBag.User = user;
            ViewBag.Group = group;
            ViewBag.Power = user.roles.Single(r => r.group.GroupId == group.GroupId).power;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(group.roles.ToList());
        }

        /// <summary>
        /// 联系信息传递
        /// </summary>
        /// <param name="data">联系人</param>
        /// <param name="letter">联系信息</param>
        /// <returns>联系视图</returns>
        [HttpPost]
        public ActionResult Contact(string data, string letter)
        {
            String[] ids = data.Split('_');
            User cur_user = GetUser("logs");
            foreach (var st in ids)
                if (st != null && st.Length > 0)
                {
                    int id = int.Parse(st);
                    User user1 = srcDB.users.Include("letters").Single(u => u.UserId == id);
                    user1.letters.Add(new Letter()
                    {
                        check = false,
                        action = letter,
                        time = DateTime.Now,
                        username = GetGroup("").groupname + "(小组)"
                    });
                    cur_user.logs.Add(new Logs
                    {
                        user = cur_user.username,
                        action = "SendLetter",
                        description = user1.username + ">:" + letter,
                        time = DateTime.Now
                    });
                    user1.logs.Add(new Logs
                    {
                        user = cur_user.username,
                        action = "NewLetter",
                        description = cur_user.username + ">:" + letter,
                        time = DateTime.Now
                    });
                }
            srcDB.SaveChanges();
            return RedirectToAction("Contact");
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="email">用户邮箱</param>
        /// <returns>联系人视图</returns>
        public ActionResult AddUser(string email)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Group current = GetGroup("roles.user");
            if ((current.roles.Select(r => r.user).ToList().Find(a => a.email == email) == null) && (srcDB.users.ToList().Find(u => u.email == email) != null) )
            {
                User newUser = srcDB.users.Include("logs").Single(u => u.email == email);
                current.roles.Add(new Role { user = newUser, group = current, power = 0 });
                Logs log = new Logs
                {
                    action = "AddUser",
                    description = newUser.username + ">:" + current.groupname,
                    time = DateTime.Now
                };
                RecordLog(log);
                newUser.logs.Add(new Logs
                {
                    user = newUser.username,
                    action = "NewAddUser", 
                    description = GetUser("").username + ">:" + current.groupname,
                    time = DateTime.Now
                });
                RecordGroupLog(log);
            }
            srcDB.SaveChanges();
            return RedirectToAction("Contact");
        }

        /// <summary>
        /// 升级用户权限
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>联系视图</returns>
        public ActionResult Upgrade(int id)
        {
            Role role = srcDB.roles.Include("user.logs").Single(r => r.RoleId == id);
            if (role.power < 1)
            {
                role.power = 1;
                Logs log = new Logs
                {
                    action = "Upgrade",
                    description = role.user.username + ">:" + GetGroup("").groupname,
                    time = DateTime.Now
                };
                RecordGroupLog(log);
                role.user.logs.Add(new Logs
                {
                    user = role.user.username,
                    action = "NewUpgrade",
                    description = GetUser("").username + ">:" + GetGroup("").groupname,
                    time = DateTime.Now
                });
                RecordLog(log);
                srcDB.SaveChanges();
            }
            return RedirectToAction("Contact");
        }

        /// <summary>
        /// 降级用户权限
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>联系视图</returns>
        public ActionResult Degrade(int id)
        {
            Role role = srcDB.roles.Include("user.logs").Single(r => r.RoleId == id);
            if (role.power > 0)
            {
                role.power = 0;
                Logs log = new Logs
                {
                    action = "Degrade",
                    description = role.user.username + ">:" + GetGroup("").groupname,
                    time = DateTime.Now
                };
                RecordGroupLog(log);
                role.user.logs.Add(new Logs
                {
                    user = role.user.username,
                    action = "NewDegrade",
                    description = GetUser("").username + ">:" + GetGroup("").groupname,
                    time = DateTime.Now
                });
                RecordLog(log);
                srcDB.SaveChanges();
            }
            return RedirectToAction("Contact");
        }

        /// <summary>
        /// 删除文件与文件夹
        /// </summary>
        /// <param name="name">文件或文件夹名</param>
        /// <param name="tag">当前所在文件类型</param>
        public void Delete(string name, int tag)
        {
  //          if (!Validation())
  //              return RedirectToAction("Index", "Home");
            Fold mfolder = GetFolder(this.HttpContext.Session["path"].ToString());
            MyFile file = mfolder.files.Find(a => a.filename == name);
            Fold zfolder = mfolder.folds.Find(a => a.foldname == name);
            if (file != null)
            {
                Logs log = new Logs
                {
                    action = "DeleteGroupFile",
                    description = this.HttpContext.Session["path"].ToString() + file.filename + "<:" + GetGroup("").groupname,
                    time = DateTime.Now
                };
                RecordGroupLog(log);
                RecordLog(log);
                DeleteFile(file);
            }
            if (zfolder != null)
            {
                Logs log = new Logs
                {
                    action = "DeleteGroupFolder",
                    description = this.HttpContext.Session["path"].ToString() + "<:" + GetGroup("").groupname,
                    time = DateTime.Now
                };
                RecordGroupLog(log);
                RecordLog(log);
                DeleteFold(zfolder);
            }
            srcDB.SaveChanges();
            //            string str = "Music";
 //           if (tag == 2)
 //               str = "Image";
 //           else if (tag == 3)
 //               str = "Doc";
 //           else if (tag == 4)
 //               str = "Files";
 //           return RedirectToAction(str);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="name">下载文件名</param>
        /// <param name="tag">所在文件类型</param>
        public void Download(string name, int tag)
        {
            Fold mfolder = GetFolder(this.HttpContext.Session["path"].ToString());
            MyFile file = mfolder.files.Find(a => a.filename == name);
            file = srcDB.files.Include("logs").Single(f => f.MyFileId == file.MyFileId);
            Logs log = new Logs
            {
                action = "GroupDownload",
                description = this.HttpContext.Session["path"] + file.filename + "<:" + GetGroup("").groupname,
                time = DateTime.Now
            };
            RecordLog(log);
            file.logs.Add(log);
            RecordGroupLog(log);
            DownloadFile(file);
            srcDB.SaveChanges();
        }

        /// <summary>
        /// 从组中删除用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>联系人视图</returns>
        public ActionResult DeleteUser(int id)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Group group = GetGroup("roles.user.logs");
            Role role = group.roles.Single(r => r.user.UserId == id);
            Logs log = new Logs
            {
                action = "DeleteUser",
                description = role.user.username + "<:" + group.groupname,
                time = DateTime.Now
            };
            role.user.logs.Add(new Logs
            {
                user = role.user.username,
                action = "NewDeleteUser",
                description = GetUser("").username + "<:" + group.groupname,
                time = DateTime.Now
            });
            RecordLog(log);
            RecordGroupLog(log);
            srcDB.roles.Remove(srcDB.roles.Single(r => r.RoleId == role.RoleId));
            srcDB.SaveChanges();
            return RedirectToAction("Contact");
        }

        /// <summary>
        /// 添加文件夹
        /// </summary>
        /// <param name="fold">文件夹名</param>
        /// <param name="tag">当前所在文件类型</param>
        /// <returns></returns>
        public int AddFolder(string fold, int tag)
        {
//            if (!Validation())
//                return RedirectToAction("Index", "Home");
            Fold folder = GetFolder(this.HttpContext.Session["path"].ToString());
            List<Fold> foldList = srcDB.folds.Single(a => a.FoldId == folder.FoldId).folds;
            for (int i = 0; i < foldList.Count; i++)
            {
                if (foldList[i].foldname == fold)
                    return 0;
            }
            foldList.Add(new Fold() { foldname = fold });
            Logs log = new Logs
            {
                action = "AddGroupFolder",
                description = this.HttpContext.Session["path"] + fold + ">:" + GetGroup("").groupname,
                time = DateTime.Now
            };
            RecordGroupLog(log);
            RecordLog(log);
            srcDB.SaveChanges();
            return 1;
//            string str = "Music";
//            if (tag == 2)
//                str = "Image";
//            else if (tag == 3)
//                str = "Doc";
//            else if (tag == 4)
//                str = "Files";
//            return RedirectToAction(str);
        }

        /// <summary>
        /// 音乐文件类型
        /// </summary>
        /// <returns>音乐文件视图</returns>
        public ActionResult Music()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = InitFolder();
            User user = GetUser("roles");
            Group group = GetGroup("");
            ViewBag.User = user;
            ViewBag.Group = group;
            ViewBag.Power = user.roles.Single(r => r.group.GroupId == group.GroupId).power;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(folder);
        }

        /// <summary>
        /// 音乐文件类型进出文件夹
        /// </summary>
        /// <param name="op">进入或者退出文件夹('+' & '-')</param>
        /// <returns>更新文件夹信息</returns>
        [HttpPost]
        public ActionResult Music(string op)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = UpdateFolder(op);
            return Json(folder);
        }

        /// <summary>
        /// 图片文件类型
        /// </summary>
        /// <returns>图片文件视图</returns>
        public ActionResult Image()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = InitFolder();
            User user = GetUser("roles");
            ViewBag.User = user;
            Group group = GetGroup("");
            ViewBag.Group = group;
            ViewBag.Power = user.roles.Single(r => r.group.GroupId == group.GroupId).power;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(folder);
        }

        /// <summary>
        /// 图片文件类型进出文件夹
        /// </summary>
        /// <param name="op">进出文件夹('+' & '-')</param>
        /// <returns>更新文件夹信息</returns>
        [HttpPost]
        public ActionResult Image(string op)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = UpdateFolder(op);
            return Json(folder);
        }

        /// <summary>
        /// 文档文件类型
        /// </summary>
        /// <returns>文档文件视图</returns>
        public ActionResult Doc()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = InitFolder();
            User user = GetUser("roles");
            ViewBag.User = user;
            Group group = GetGroup("");
            ViewBag.Group = group;
            ViewBag.Power = user.roles.Single(r => r.group.GroupId == group.GroupId).power;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(folder);
        }

        /// <summary>
        /// 文档文件进出文件夹('-' & '+')
        /// </summary>
        /// <param name="op">进出操作('-' & '+')</param>
        /// <returns>更新文件夹信息</returns>
        [HttpPost]
        public ActionResult Doc(string op)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = UpdateFolder(op);
            return Json(folder);
        }

        /// <summary>
        /// 所有文件类型
        /// </summary>
        /// <returns></returns>
        public ActionResult Files()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = InitFolder();
            User user = GetUser("roles");
            Group group = GetGroup("");
            ViewBag.User = user;
            ViewBag.Group = group;
            ViewBag.Power = user.roles.Single(r => r.group.GroupId == group.GroupId).power;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(folder);
        }

        /// <summary>
        /// 所有文件进出文件夹
        /// </summary>
        /// <param name="op">进出操作</param>
        /// <returns>更新文件夹信息</returns>
        [HttpPost]
        public ActionResult Files(string op)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = UpdateFolder(op);
            return Json(folder);
        }

        /// <summary>
        /// 显示操作日志
        /// </summary>
        /// <returns>操作日志</returns>
        public ActionResult LogManager()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Group group = GetGroup("logs");
            group.logs.ForEach(a => a.description = translate(a));
            User user = GetUser("");
            ViewBag.User = user;
            ViewBag.Group = group;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(group.logs.OrderByDescending(u => u.time).ToList());
        }

        /// <summary>
        /// 现实组信息
        /// </summary>
        /// <returns>组信息视图</returns>
        public ActionResult Info()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Group group = GetGroup("fold");
            User user = GetUser("roles");
            int size = GetSize(group.fold);
            ViewBag.Manager = group.creator.username;
            ViewBag.User = user;
            ViewBag.Size = size;
            ViewBag.Space = space - size;
            ViewBag.Group = group;
            ViewBag.Power = user.roles.Single(r => r.group.GroupId == group.GroupId).power;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(group);
        }

        /// <summary>
        /// 编辑组信息
        /// </summary>
        /// <returns>组编辑视图</returns>
        public ActionResult EditGroup()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Group group = GetGroup("");
            User user = GetUser("roles");
            ViewBag.User = user;
            ViewBag.Group = group;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(group);
        }

        /// <summary>
        /// 组信息更改
        /// </summary>
        /// <param name="group">组信息</param>
        /// <returns>组信息视图</returns>
        [HttpPost]
        public ActionResult EditGroup(Group group)
        {
            Group current = GetGroup("");
            current.introduction = group.introduction;
            current.groupname = group.groupname;
            Logs log = new Logs
            {
                action = "EditGroup",
                time = DateTime.Now,
                description = current.groupname,
            };
            RecordLog(log);
            RecordGroupLog(log);
            srcDB.SaveChanges();
            return RedirectToAction("Info");
        }

        /// <summary>
        /// 文件下载浏览
        /// </summary>
        /// <param name="name">文件名</param>
        /// <param name="tag">文件类型</param>
        /// <returns></returns>
        public ActionResult FileDetail(string name, int tag)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = GetFolder(this.HttpContext.Session["path"].ToString());
            MyFile file = folder.files.Single(u => u.filename == name);
            file = srcDB.files.Include("logs").Single(u => u.MyFileId == file.MyFileId);
            file.logs.ForEach(u => u.description = translate(u));
            ViewBag.User = GetUser("");
            ViewBag.Group = GetGroup("");
            ViewBag.letterCount = GetUncheckedLetters();
            return View(file.logs.OrderByDescending(u => u.time).ToList());
        }

        /// <summary>
        /// 用户验证
        /// </summary>
        /// <returns>是否验证通过</returns>
        private bool Validation()
        {
            return this.HttpContext.Session["user"] != null && this.HttpContext.Session["group"] != null;
        }

        /// <summary>
        /// 初始化到母文件夹
        /// </summary>
        /// <returns>母文件夹</returns>
        private Fold InitFolder()
        {
            Fold folder = GetFolder("/");
            this.HttpContext.Session["path"] = "/";
            folder.files = folder.files.Select(a => srcDB.files.Include("creator").Single(u => a.MyFileId == u.MyFileId)).ToList();
            return folder;
        }

        /// <summary>
        /// 跳转到新文件夹
        /// </summary>
        /// <param name="op">进入或者跳出</param>
        /// <returns>新文件夹</returns>
        private Fold UpdateFolder(string op)
        {
            if (op[0] == '+')
            {
                this.HttpContext.Session["path"] =
                    this.HttpContext.Session["path"].ToString() + op.Substring(1) + "/";
            }
            else if (op[0] == '-')
            {
                string str = this.HttpContext.Session["path"].ToString();
                int t = str.Length - 1;
                while (t > 0 && str[t - 1] != '/')
                    --t;
                this.HttpContext.Session["path"] = str.Substring(0, t);
            }
            Fold folder = GetFolder(this.HttpContext.Session["path"].ToString());
            folder.files = folder.files.Select(a => srcDB.files.Include("creator").Single(u => a.MyFileId == u.MyFileId)).ToList();
            return folder;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="file"></param>
        private void DeleteFile(MyFile file)
        {
            System.IO.File.Delete(Server.MapPath(file.url).Substring(0, Server.MapPath("").Length - 5)+file.url);
            srcDB.files.Remove(file);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="file">文件对象</param>
        private void DownloadFile(MyFile file)
        {
            //ASP.NET下载文件(弹出打开保存文件对话框) 
            try
            {
                //FileName--要下载的文件名
                string FileName = Server.MapPath(file.url).Substring(0, Server.MapPath("").Length - 5) + file.url;

                FileInfo DownloadFile = new FileInfo(FileName);
                if (DownloadFile.Exists)
                {
                    file.hot += 1;
                    srcDB.SaveChanges();
                    Response.Clear();
                    Response.ClearHeaders();
                    Response.Buffer = false;
                    Response.ContentType = "application/octet-stream";
                    Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.UTF8));
                    Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
                    Response.WriteFile(DownloadFile.FullName);
                    Response.Flush();
                    Response.End();

                    string[] strArray = FileName.Split('_');
                    System.IO.File.Move(FileName, strArray[strArray.Length - 1]);
                }
                else
                {
                    //文件不存在
                }
            }
            catch
            {
                //打开时异常了
            }

        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="folder">文件夹对象</param>
        private void DeleteFold(Fold folder)
        {
            folder = srcDB.folds.Include("folds").Include("files").Single(a => a.FoldId == folder.FoldId);
            List<Fold> folders = folder.folds.ToList();
            folders.ForEach(a => DeleteFold(a));
            List<MyFile> files = folder.files.ToList(); 
            files.ForEach(a => DeleteFile(a));
            srcDB.folds.Remove(folder);
        }

        /// <summary>
        /// 获取文件夹
        /// </summary>
        /// <param name="url">文件夹路径</param>
        /// <returns>文件夹</returns>
        private Fold GetFolder(string url)
        {
            string[] paths = url.Split('/');
            Group group = GetGroup("fold");
            Fold result = group.fold;
            foreach (var path in paths)
            {
                if (path.Length > 0)
                    result = srcDB.folds
                              .Include("folds")
                              .ToList()
                              .Single(u => u.FoldId == result.FoldId)
                              .folds
                              .ToList()
                              .Single(u => u.foldname == path);
            }

            result = srcDB.folds.Include("folds")
                .Single(u => u.FoldId == result.FoldId);
            return result;
        }

        /// <summary>
        /// 获取组信息
        /// </summary>
        /// <param name="url">组信息获取列表</param>
        /// <returns>组</returns>
        private Group GetGroup(string url)
        {
            if (url.Length > 0)
            {
                return srcDB.groups
                        .Include(url)
                        .ToList()
                        .Single(u => u.GroupId == int.Parse(
                            this.HttpContext.Session["group"].ToString()));
            }
            else
            {
                return srcDB.groups
                        .ToList()
                        .Single(u => u.GroupId == int.Parse(
                            this.HttpContext.Session["group"].ToString()));
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="url">用户信息列表</param>
        /// <returns>用户</returns>
        private User GetUser(string url)
        {
            if (url.Length > 0)
            {
                return srcDB.users
                        .Include(url)
                        .ToList()
                        .Single(u => u.UserId == int.Parse(
                            this.HttpContext.Session["user"].ToString()));
            }
            else
            {
                return srcDB.users
                        .ToList()
                        .Single(u => u.UserId == int.Parse(
                            this.HttpContext.Session["user"].ToString()));
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="FileData">上传内容</param>
        /// <param name="folder">上传路径</param>
        /// <param name="name">名字</param>
        /// <returns>上传响应</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ContentResult Import(HttpPostedFileBase FileData, string folder, string name)
        {
            string result = "";

            if (null != FileData)
            {
                try
                {
                    result = Path.GetFileName(FileData.FileName);//获得文件名
                    string ext = Path.GetExtension(FileData.FileName).ToLower();//获得文件扩展名
                    //           string saveName = "uploadfile" + ext;//实际保存文件名
                    string saveName = result;// +ext;

                    Fold currentFolder = GetFolder(this.HttpContext.Session["path"].ToString());
                    if (currentFolder.files.Find(u => u.filename == saveName) != null)
                        return Content("x");
   
                    MyFile newFile = new MyFile() { createTime = DateTime.Now.ToString() };
                    newFile.filename = saveName;
                    newFile.createTime = DateTime.Now.ToLocalTime().ToString();
                    newFile.size = FileData.ContentLength;
                    newFile.creator = GetUser("");
                    if (ext == ".mp3" || ext == ".avi" || ext == "wav" || ext == ".wma")
                        newFile.tag = 1;
                    else if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".gif")
                        newFile.tag = 2;
                    else if (ext == ".doc" || ext == ".docx" || ext == ".xls" || ext == ".xlsx" || ext == ".pdf" || ext==".ppt" || ext==".pptx")
                        newFile.tag = 3;
                    else
                        newFile.tag = 4;
                    Logs log = new Logs
                    {
                        action = "ImportGroupFile",
                        time = DateTime.Now,
                        description = this.HttpContext.Session["path"] + newFile.filename + ">:" + GetGroup("").groupname
                    };
                    RecordGroupLog(log);
                    RecordLog(log);
                    currentFolder.files.Add(newFile);
                    srcDB.SaveChanges();
                    int fileId = currentFolder.files.Single(u => u.filename == saveName).MyFileId;
                    saveName = fileId + "_" + saveName;
                    currentFolder.files.Single(u => u.MyFileId == fileId).url = "Content/files/" + saveName;
                    srcDB.SaveChanges();
                    saveFile(FileData, folder, saveName);//保存文件
                    if (newFile.tag == 2)
                    {
                        string phyPath = Request.MapPath("~" + folder + "/");
                        //生成缩略图
                        System.Drawing.Image srcImage = System.Drawing.Image.FromFile(phyPath + saveName);
                        int width = 90 * srcImage.Width / srcImage.Height;
                        System.Drawing.Image newImage = srcImage.GetThumbnailImage(width, 90, null, IntPtr.Zero);

                        newImage.Save(phyPath + "thumbnail/" + saveName);
                    }
                }
                catch
                {
                    result = "";
                }
            }
            return Content(result);
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="postedFile">上传数据</param>
        /// <param name="filepath">文件路径</param>
        /// <param name="saveName">保存名字</param>
        [NonAction]
        private void saveFile(HttpPostedFileBase postedFile, string filepath, string saveName)
        {
            string phyPath = Request.MapPath("~" + filepath + "/");
            if (!Directory.Exists(phyPath))
            {
                Directory.CreateDirectory(phyPath);
            }
            try
            {
                postedFile.SaveAs(phyPath + saveName);
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);

            }
        }
        
        /// <summary>
        /// 聊天室
        /// </summary>
        /// <returns>聊天室视图</returns>
        public ActionResult ChatRoom()
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Fold folder = InitFolder();
            User user = GetUser("roles");
            Group group = GetGroup("roles.user");
            ViewBag.User = user;
            ViewBag.Group = group;
            ViewBag.Power = user.roles.Single(r => r.group.GroupId == group.GroupId).power;
            ViewBag.letterCount = GetUncheckedLetters();
            return View(srcDB.groups.Include("chatRoom").Single(u => u.GroupId == group.GroupId).chatRoom.ToList());
        }

        /// <summary>
        /// 聊天室更新
        /// </summary>
        /// <param name="msg">新加消息</param>
        [HttpPost]
        public void ChatRoom(string msg)
        {
            Group group = GetGroup("roles.user");
            User user = GetUser("roles");
            srcDB.groups.Include("chatRoom").Single(u => u.GroupId == group.GroupId).chatRoom.Add(new Chatroom { username = user.username, action = msg, time=DateTime.Now.ToLocalTime()});
            srcDB.SaveChanges();
        }

        /// <summary>
        /// 添加消息
        /// </summary>
        /// <param name="num"></param>
        /// <returns>消息数据</returns>
        [HttpPost]
        public ActionResult ChatRoomAjax(int num)
        {
            Group group = GetGroup("roles.user");
            List<Chatroom> result = srcDB.groups.Include("chatRoom").Single(u => u.GroupId == group.GroupId).chatRoom.ToList();
            return Json(result);
        }

        /// <summary>
        /// 发送邮件视图
        /// </summary>
        /// <param name="emailaddresses">邮件地址</param>
        /// <returns>邮件发送视图</returns>
        public ActionResult SendEmail(string emailaddresses)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            Email email = new Email();
            email.emailaddresses = emailaddresses;
            ViewBag.User = GetUser("");
            ViewBag.letterCount = GetUncheckedLetters();
            return View(email);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="sendemail">邮件信息</param>
        /// <returns>联系人视图</returns>
        [HttpPost]
        public ActionResult SendEmails(Email sendemail)
        {
            String[] emails = sendemail.emailaddresses.Split(';');
            User cur_user = GetUser("logs");
            foreach (string email in emails)
            {
                if (email != "")
                {
                    SendMail(sendemail.subject, sendemail.message, email);
                    Logs new_log = new Logs
                    {
                        user = cur_user.username,
                        action = "SendEmail",
                        description = email + ">:" + sendemail.subject + "%" + sendemail.message,
                        time = DateTime.Now
                    };
                    cur_user.logs.Add(new_log);
                    User user1 = srcDB.users.Include("logs").Single(s => s.email == email);
                    user1.logs.Add(new Logs
                    {
                        user = cur_user.username,
                        action = "NewEmail",
                        description = cur_user.username + ">:" + sendemail.subject + "%" + sendemail.message,
                        time = DateTime.Now
                    });
                }
            }
            return RedirectToAction("Contact");

        }

        /// <summary>
        /// 发送邮件API
        /// </summary>
        /// <param name="subject">主题</param>
        /// <param name="message">信息</param>
        /// <param name="address">地址</param>
        public void SendMail(string subject, string message, string address)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.Subject = subject;
                mail.Body = message;
                mail.From = new MailAddress("fairylandnote@gmail.com", "fairyworld资料管理平台");
                mail.To.Add(address);
                // send the e-mail
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com"; // SMTP Server Address
                smtp.Port = 587;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential("fairylandnote@gmail.com", "fairyland123");
                smtp.EnableSsl = true;
                smtp.Send(mail);
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }

        }

        /// <summary>
        /// 搜索文件
        /// </summary>
        /// <param name="folder">文件夹名</param>
        /// <param name="filesSearch">文件列表</param>
        public void SearchFiles(Fold folder, List<MyFile> filesSearch)
        {
            foreach (Fold subfolder in folder.folds)
                SearchFiles(subfolder, filesSearch);
            foreach (MyFile file in folder.files)
            {
                int flag = file.filename.IndexOf(HttpContext.Session["searchkey"].ToString());
                if (flag != -1)
                    filesSearch.Add(file);
            }
        }

        [HttpPost]
        public int Nothing()
        {
            return 0;
        }

        /// <summary>
        /// 搜索内容
        /// </summary>
        /// <param name="key">关键字</param>
        /// <returns>文件搜索视图</returns>
        public ActionResult Search(string key)
        {
            if (!Validation())
                return RedirectToAction("Index", "Home");
            HttpContext.Session["searchkey"] = key;
            Fold folder = GetFolder("/");
            Group group = GetGroup("");
            User user = GetUser("roles");
            ViewBag.User = user;
            ViewBag.Group = group;
            ViewBag.Power = user.roles.Single(r => r.group.GroupId == group.GroupId).power;
            List<MyFile> filesSearch = new List<MyFile>();
            SearchFiles(folder, filesSearch);
            ViewBag.letterCount = GetUncheckedLetters();
            return View(filesSearch);
        }

        /// <summary>
        /// 获取未阅读的私信
        /// </summary>
        /// <returns>未阅读私信个数</returns>
        public int GetUncheckedLetters()
        {
            User user = GetUser("letters");
            int count = 0;
            for (int i = 0; i < user.letters.Count; i++)
            {
                if (user.letters[i].check == false)
                    count++;
            }
            return count;
        }

        /// <summary>
        /// 获取文件夹大小
        /// </summary>
        /// <param name="folder">文件夹名</param>
        /// <returns>大小</returns>
        private int GetSize(Fold folder)
        {
            int size = 0;
            folder = srcDB.folds.Include("folds").Include("files").Single(u => u.FoldId == folder.FoldId);
            folder.files.ForEach(u => size += u.size);
            folder.folds.ForEach(u => size += GetSize(u));
            return size;
        }

        /// <summary>
        /// 记录用户操作
        /// </summary>
        /// <param name="log">操作日志</param>
        private void RecordLog(Logs log)
        {
            User user = GetUser("logs");
            log.user = user.username;
            user.logs.Add(log);
        }

        /// <summary>
        /// 记录组操作日志
        /// </summary>
        /// <param name="log">操作日志</param>
        private void RecordGroupLog(Logs log)
        {
            Group group = GetGroup("logs");
            log.user = GetUser("").username;
            group.logs.Add(log);
        }
        
        /// <summary>
        /// 操作日志翻译
        /// </summary>
        /// <param name="log">操作日志</param>
        /// <returns>翻译结果</returns>
        private string translate(Logs log)
        {
            int i;
            string st1 = "", st2 = "";
            switch (log.action)
            {
                case "EditUser":
                    return "编辑个人信息";
                case "DeleteFile":
                    return "删除文件" + log.description;
                case "DeleteFolder":
                    return "删除文件夹" + log.description;
                case "Download":
                    return "下载文件" + log.description;
                case "AddFolder":
                    return "创建文件夹" + log.description;
                case "SendLetter":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "向" + st1 + "发送私信:" + st2;
                case "NewLetter":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "收到" + st1 + "发送的私信:" + st2;
                case "CheckLetter":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "阅读" + st1 + "发送的私信:" + st2;
                case "CreateGroup":
                    return "创建组" + log.description;
                case "DeleteGroup":
                    return "删除组" + log.description;
                case "LeaveGroup":
                    return "退出组" + log.description;
                case "SendEmail":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    return "发送email至" + st1;
                case "NewEmail":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    return "接受来自" + st1 + "的email";
                case "AddUser":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "添加用户" + st1 + "至组" + st2;
                case "NewAddUser":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "被用户" + st1 + "邀请至组" + st2;
                case "Upgrade":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "提升" + st1 + "为组" + st2 + "的管理员";
                case "NewUpgrade":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "被" + st1 + "提升为组" + st2 + "的管理员";
                case "Degrade":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "剥夺" + st1 + "在组" + st2 + "的管理员权限";
                case "NewDegrade":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "被" + st1 + "剥夺在组" + st2 + "的管理员权限";
                case "DeleteGroupFile":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "删除组" + st2 + "的文件" + st1;
                case "DeleteGroupFolder":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "删除组" + st2 + "的文件夹" + st1;
                case "GroupDownload":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "下载组" + st2 + "的文件" + st1;
                case "DeleteUser":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "驱逐组" + st2 + "的用户" + st1;
                case "NewDeleteUser":
                    i = 0;
                    while (log.description[i] != '<' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "被" + st2 + "从组" + st1 + "驱逐";
                case "AddGroupFolder":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "在组" + st2 + "中创建文件夹" + st1;
                case "EditGroup":
                    return "更改组" + log.description + "的信息";
                case "ImportFile":
                    return "上传文件到" + log.description;
                case "ImportGroupFile":
                    i = 0;
                    while (log.description[i] != '>' || log.description[i + 1] != ':')
                        ++i;
                    st1 = log.description.Substring(0, i);
                    st2 = log.description.Substring(i + 2);
                    return "上传文件" + st1 + "到组" + st2;
            }
            return "";
        }
    }

}
